<?php

class Application_Model_OtherMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Other');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Other $other)
	{
		
		
		$objectMapper = new Application_Model_ObjectMapper();
		$row = $objectMapper->save($other);
		//TODO set the object save function to return the id of the object saved
		//$where = array('name = ?' => (string)$object->getName());
		$other->setObjectId($row);
		
		$data = array(
				'id_object' 	=> $other->getObjectId(),
				'category'   	=> $other->getCategory(),
		);
		
		if (null === ($id = $other->getOtherId())) {
			unset($data['id_other']);
			return $this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_other = ?' => $id));
			return $id;
		}
		
		
	}
	
	public function find($id, Application_Model_Other $other)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$other->setOtherId($row->id_other);
		$other->setObjectId($row->id_object);
		$other->setCategory($row->category);
		$objectMapper = new Application_Model_ObjectMapper();
		$other = $objectMapper->find($other->getObjectId(), $other);
		
		return $other;
	}
	
	public function delete($id)
	{

		$other = new Application_Model_Other();
		$objectMapper = new Application_Model_ObjectMapper();
		$other = $this->find($id, new Application_Model_Other());
		
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_other = ?' => $id));
		}
		
		$objectMapper->delete($other->getObjectId());
		
	
	}
	
	public function indexBuilder(Zend_Search_Lucene_Document $doc, Application_Model_Other $other)
	{
		$objectMapper = new Application_Model_ObjectMapper();
		$doc->addField(Zend_Search_Lucene_Field::Text('category', $other->getCategory(), 'utf-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('objectType', 'other', 'utf-8'));
		$doc = $objectMapper->indexBuilder($doc, $other);
	
		return $doc;
	}
}
